package org.example.userservice.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.example.userservice.VO.UserVO;
import org.example.userservice.parsetoken.ParseToken;
import org.example.userservice.producer.LogProducer;
import org.example.userservice.untils.JWTUntils;
import org.example.userservice.entity.User;
import org.example.userservice.mapper.UserMapper;
import org.example.userservice.openfeign.PermissionClient;
import org.example.userservice.untils.JudgeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    PermissionClient permissionClient;

    @Autowired
    private LogProducer logProducer;

    // 用户注册
    public void register(User user,HttpServletRequest request) {
        // 设置用户ID
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        user.setUserId(snowflake.nextId());
        // 设置用户创建时间
        user.setGmtCreate(new Timestamp(System.currentTimeMillis()));
        // 写入数据库
        userMapper.insert(user);
        // 记录日志
        logProducer.sendLog(user.getUserId(),"REGISTER",request.getRemoteAddr(),"用户注册");
        // 绑定用户权限
        permissionClient.bindDefaultRole(user.getUserId());
    }

    // 用户登录
    public String login(User input,HttpServletRequest request) {
        // 根据用户名查询用户
        User user = userMapper.findByUsername(input.getUsername());
        // 校验密码是否一致
        if (user != null && user.getPassword().equals(input.getPassword())) {
            String rolecode = permissionClient.getUserRoleCode(user.getUserId());
            logProducer.sendLog(user.getUserId(),"LOGIN",request.getRemoteAddr(),"用户登录");
            return JWTUntils.generateToken(user.getUserId(),rolecode); // 登录成功生成 Token
        }
        // 登录失败抛出异常
        throw new RuntimeException("用户名或密码错误！");
    }

    // 用户分页
    public List<UserVO> listUsers(HttpServletRequest request) {

        Long currentUserId = ParseToken.getUserIdFromToken(request);
        String roleCode = ParseToken.getRoleCodeFromToken(request);

        // 超管返回全部
        if (JudgeUtils.isSuperAdmin(roleCode)) {
            return userMapper.findAll();
        }

        // 管理员返回普通用户
        if (JudgeUtils.isAdmin(roleCode)) {
            return userMapper.findByRole(permissionClient.getNormalUser());
        }

        // 普通用户仅查自己
        return Collections.singletonList(userMapper.findByIdVO(currentUserId));
    }

    public UserVO selectUserById(Long userId,HttpServletRequest request) {
        Long currentUserId = ParseToken.getUserIdFromToken(request);
        String roleCode = ParseToken.getRoleCodeFromToken(request);


        if (JudgeUtils.isSuperAdmin(roleCode)) {
            return userMapper.findByIdVO(userId);
        }

        if (JudgeUtils.isAdmin(roleCode)) {
            // 不能查询管理和超管
            String targetRole = permissionClient.getUserRoleCode(userId);
            if (!"user".equals(targetRole)) {
                return null;
            }
        }

        if(!currentUserId.equals(userId)){
            return null;
        }

        return userMapper.findByIdVO(currentUserId);
    }


    // 更新用户数据
    public String update(User user,HttpServletRequest request) {
        Long currentUserId = ParseToken.getUserIdFromToken(request);
        String roleCode = ParseToken.getRoleCodeFromToken(request);

        // 超管：可以修改任意用户
        if (JudgeUtils.isSuperAdmin(roleCode)) {
            userMapper.update(user);
            logProducer.sendLog(user.getUserId(),"UPDATE",request.getRemoteAddr(),"更新");
            return "修改成功！";
        }

        // 管理员：只能修改普通用户
        if (JudgeUtils.isAdmin(roleCode)) {
            // 不能修改超管或管理员
            String targetRole = permissionClient.getUserRoleCode(user.getUserId());
            if (!"user".equals(targetRole)) {
                return "管理员不能修改其他管理员或超管！";
            }
            userMapper.update(user);
            logProducer.sendLog(user.getUserId(),"UPDATE",request.getRemoteAddr(),"更新");
            return "修改成功！";
        }

        // 普通用户：只能修改自己
        if (!currentUserId.equals(user.getUserId())) {
            return "普通用户只能修改自己的信息！";
        }
        userMapper.update(user);
        logProducer.sendLog(user.getUserId(),"UPDATE",request.getRemoteAddr(),"更新");
        return "修改成功！";
    }
    // 用户修改密码
    public String resetPassword(User user,HttpServletRequest request) {
        Long currentUserId = ParseToken.getUserIdFromToken(request);
        String roleCode = ParseToken.getRoleCodeFromToken(request);

        // 超管：可以修改任意用户
        if (JudgeUtils.isSuperAdmin(roleCode)) {
            userMapper.resetPassword(user);
            logProducer.sendLog(user.getUserId(),"RESETPASSWORD",request.getRemoteAddr(),"改密");
            return "修改成功！";
        }

        // 管理员：只能修改普通用户
        if (JudgeUtils.isAdmin(roleCode)) {
            // 不能修改超管或管理员
            String targetRole = permissionClient.getUserRoleCode(user.getUserId());
            if (!"user".equals(targetRole)) {
                return "管理员不能修改其他管理员或超管！";
            }
            userMapper.resetPassword(user);
            logProducer.sendLog(user.getUserId(),"RESETPASSWORD",request.getRemoteAddr(),"改密");
            return "修改成功！";
        }

        // 普通用户：只能修改自己
        if (!currentUserId.equals(user.getUserId())) {
            return "普通用户只能修改自己的密码！";
        }
        userMapper.resetPassword(user);
        logProducer.sendLog(user.getUserId(),"RESETPASSWORD",request.getRemoteAddr(),"改密");
        return "修改成功！";
    }
}